import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Row, Col, Form, Card, Select,Icon,List,Button,Input,
Modal,Table} from 'antd';

import styles from './CompanyIndex.less';

const { Option } = Select;
const FormItem = Form.Item;

const states = {"[10]":'未开场', "[20]":"已开场","[30]":"已截止","[40]":"已结束"};
const stateChildren = [];
Object.keys(states).forEach( (key) => {
  stateChildren.push(<Option value={key}>{states[key]}</Option>);
});

// 活动详情面板
const ActInfoMedal = Form.create()(props => {
  const {
    actMedalVisible,
    cancelActModal,
    loading,
    form,
    actId,
    prdData,
    handleStandardTableChange,
    doQueryPrd,
  } = props;

  const paginationProps = {
    showSizeChanger: true,
    showQuickJumper: true,
    ...prdData.pagination,
  };

  const openNewWid = (url)=>{
    window.open(url, '_blank');
  };

  const columns = [
    {
      title: '作品图',
      dataIndex: 'theme_img',
      render: (text,record) =>{
        return <img onClick={()=>openNewWid(record.url)} alt="作品封面" src={text} width="40px" height="80px" />;
      },
    },
    {
      title: '作品ID',
      dataIndex: 'aup_id',
    },
    {
      title: '审核',
      dataIndex: 'state_desc',
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
    },
    {
      title: '数据1',
      dataIndex: 'data1',
    },
    {
      title: '数据2',
      dataIndex: 'data2',
    },
    {
      title: '审核备注',
      dataIndex: 'note',
      render:(text)=>{
        let tmp ='-';
        if (text && text.length>10){
          tmp = `${text.slice(0,10)}...`;
        }
        return (
          <span>{tmp}</span>
        );
      },
    },
    {
      title: '奖金*元',
      dataIndex: 'reward_amt',
      render:(text)=>{
        let tmp = 0;
        if (text){
          tmp = text/100;
        }
        return (
          <span style={{color:'red'}}>{tmp}</span>
        );
      },
    },
    {
      title: '创建时间',
      dataIndex: 'fmt_create_time',
    },
    {
      title: '更新时间',
      dataIndex: 'fmt_update_time',
    },
  ];
  let prdPageSize = 10;

  // Table自身事件
  const tableHandel = (p)=>{
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      prdPageSize = p.pageSize;
      const params = {
        'pageNum': p.current-1,
        'pageSize': prdPageSize,
        'withTotalPage': 1,
        'mobile':fieldsValue.mobile||null,
        'findStates':fieldsValue.findSt||null,
        'actId':actId,
      };
      handleStandardTableChange(p,params);
    });
  };

  // 查询作品
  const doQuery = ()=>{
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const params = {
        'findStates': fieldsValue.findSt || null,
        'mobile': fieldsValue.mobile || null,
        'actId':actId,
        'pageSize':prdPageSize,
        'pageNum': 0,
        'withTotalPage': 1,
      };
      doQueryPrd(params);
    });
  };

  const st = {"":'[不限]',"[10]":'新建', "[20]":"审核中","[30]":"审核通过","[40]":"审核不通过"};
  const stChildren = [];
  Object.keys(st).forEach( (key) => {
    stChildren.push(<Option value={key}>{st[key]}</Option>);
  });

  // 筛选条件
  const infoHeadeForm = ()=> {
    const { getFieldDecorator } = form;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={6} sm={24}>
            <FormItem label="审核状态">
              {getFieldDecorator('findSt')(
                <Select placeholder="请选择">
                  {stChildren}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="手机号">
              {getFieldDecorator('mobile')(
                <Input placeholder="输入手机号" />
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit" icon="search" onClick={doQuery}>
                查询
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  };

  return (
    <Modal
      title="活动作品一览"
      style={{top: '5px'}}
      visible={actMedalVisible}
      onCancel={() => cancelActModal()}
      width='1100px'
      maskClosable={false}
      footer={null}
    >
      <div className={styles.sedTableListForm}>{infoHeadeForm()}</div>
      <Table
        loading={loading}
        dataSource={prdData.actPrdLis}
        columns={columns}
        pagination={paginationProps}
        onChange={tableHandel}
        rowKey="PRDID"
      />
    </Modal>
  );
});



/** eslint react/no-array-index-key: 0
 *  绑定数据
 * */
@Form.create()
@connect(({ list, loading }) => ({
  list,
  companyInfo:list.companyInfo,
  loading: loading.models.list,
  prdData:list.prdData,// 作品列表
}))

export default class CoverCardList extends PureComponent {
  state = {
    pageNum: 0,
    title:null,
    findStates:null,
    actMedalVisible:false,
    actId:null,
    actNum:0,
  };

  componentDidMount() {
    const { dispatch } = this.props;
    const {pageNum,title,findStates,actNum} = this.state;
    dispatch({
      type: 'list/getCoopActInfoList',
      payload: {
        pageNum,
        title,
        actNum,
        findStates,
      },
    });
  };

  // table改变事件 LQ
  handleStandardTableChange = (pagination,params) => {
    const { dispatch} = this.props;
    this.setState({
      actNum : pagination.current-1,
    });
    dispatch({
      type: 'list/pageGetActPrd',
      payload: params,
    });
  };

  // 主页面查询
  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      this.setState({
        title: fieldsValue.title || null,
        findStates: fieldsValue.findStates || null,
      });
      const { pageNum } = this.state;
      dispatch({
        type: 'list/getCoopActInfoList',
        payload: { title:fieldsValue.title,findStates:fieldsValue.findStates,pageNum },
      });
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      title: null,
      findStates:null,
      pageNum:0,
      actNum:0,
    });
    dispatch({
      type: 'list/getCoopActInfoList',
      payload: {
        title:null,
        findStates:null,
        pageNum:0,
      },
    });
  };


  actInfoHandle =(actId)=>{// 活动作品详情
    this.setState({
      actMedalVisible:true,
      actId:actId||0,
    });
    const {dispatch,actNum} = this.props;
    const params = {
      'pageNum':actNum,
      'pageSize': 10,// 默认10条一页
      'withTotalPage':1,
      'actId':actId,
    };
    dispatch({
      type: 'list/pageGetActPrd',// 分页获取活动作品列表
      payload: params,
    });
  };

  cancelActModal = ()=>{ // 取消详情弹窗
    this.setState({
      actMedalVisible:false,
      actId:null,
      actNum:0,
    })
  };



  // 作品查询 LQ
  doQueryPrd = (params) => {
    const { dispatch} = this.props;
    this.setState({
      actNum : 0,
    });
    dispatch({
      type: 'list/pageGetActPrd',
      payload: params,
    });
  };


  render() {
    const {
      list: { list = []},
      companyInfo,
      loading,
      prdData,
      form,
    } = this.props;
    const { getFieldDecorator} = form;
    const {actMedalVisible,actId} = this.state;

    // 顶级方法
    const actInfoParentMethod = {
      cancelActModal:this.cancelActModal,
      handleStandardTableChange:this.handleStandardTableChange,
      doQueryPrd:this.doQueryPrd,
    };

    /* eslint-disable no-script-url */
    const cardList = list ? (
      <List
        rowKey="act_id"
        loading={loading}
        grid={{ gutter: 24, xl: 4, lg: 3, md: 3, sm: 2, xs: 1 }}
        dataSource={list}
        renderItem={item => (
          <List.Item>
            <Card
              className={styles.card}
              cover={<img alt={item.title} src={item.theme_img} style={{"height":160}} />}
            >
              <Card.Meta
                title={item.title}
                description={item.desc}
              />
              <div className={styles.activityDesc}>
                <div className={styles.activityDescType}>
                  {item.state_desc} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                  <a href="javascript:;" onClick={() => this.actInfoHandle(item.act_id)}>明细</a>
                </div>
                <div className={styles.activityDescTime}>活动时间 : {item.start_time}~{item.end_time}</div>
              </div>
            </Card>
          </List.Item>
        )}
      />
    ) : null;

    const Info = ({ title, value, bordered,iconFont }) => (
      <div className={styles.headerInfo}>
        <Icon className={styles.headerInfo_icon} type={iconFont} />
        <div className={styles.headerInfo_other}>
          <span style={{color:'green'}}>{title}</span>
          <p>{value}</p>
          {bordered && <em />}
        </div>
      </div>
    );

    let reward = 0;
    let actCnt = 0;
    let prodCnt = 0;
    let userCnt = 0;

    if (companyInfo!=null && undefined!==companyInfo){
      reward = companyInfo.reward || 0;
      actCnt = companyInfo.actCnt || 0;
      prodCnt = companyInfo.prodCnt || 0;
      userCnt = companyInfo.userCnt || 0;
    }

    return (
      <div className={styles.coverCardList}>
        <Card>
          <Row>
            <Col sm={6} xs={24}>
              <Info title="挑战收益总额" value={`${reward/100}元`} iconFont="pay-circle-o" bordered />
            </Col>
            <Col sm={6} xs={24}>
              <Info title="参与挑战总数" value={actCnt} iconFont="pie-chart" bordered />
            </Col>
            <Col sm={6} xs={24}>
              <Info title="参赛作品总数" value={prodCnt} iconFont="pie-chart" bordered />
            </Col>
            <Col sm={6} xs={24}>
              <Info title="旗下人员总数" value={userCnt} iconFont="user" />
            </Col>
          </Row>
        </Card>
        <div className={styles.tableListForm}>
          <Form onSubmit={this.handleSearch} layout="inline">
            <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
              <Col md={8} sm={24}>
                <FormItem label="活动状态">
                  {getFieldDecorator('findStates')(
                    <Select placeholder="请选择" style={{ width: '100%' }}>
                      {stateChildren}
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col md={8} sm={24}>
                <FormItem label="活动标题">
                  {getFieldDecorator('title')(<Input placeholder="请输入" />)}
                </FormItem>
              </Col>
              <Col md={8} sm={24}>
                <span className={styles.submitButtons}>
                  <Button type="primary" htmlType="submit">
                    查询
                  </Button>
                  <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                    重置
                  </Button>
                </span>
              </Col>
            </Row>
          </Form>
        </div>
        <div className={styles.cardList}>{cardList}</div>
        <ActInfoMedal
          {...actInfoParentMethod}
          actMedalVisible={actMedalVisible}
          actId={actId}
          loading={loading}
          prdData={prdData}
        />
      </div>
    );
  }
}
